<template>
  <div>
    <p>home页面</p>
    <button @click="logout">点击退出</button>
    <p>
      尝试图片的压缩的2种方式,1.插件imageConversion
      2.canvas将img的file转换为base64进行压缩,element before-upload返回promise对象
    </p>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
// import * as imageConversion from 'image-conversion' // 图片压缩
export default {
  name: 'HomeView',
  props: {},
  components: {},
  data () {
    return {
      imageUrl: ''
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    logout () {
      this.$store.commit('user/DELE_TOKEN')
      this.$router.push('/login?redirect=' + this.$route.fullPath)
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      console.log(this)
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      // const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG格式!')
      }
      // return new Promise((resolve) => {
      //   if (isLt2M) {
      //     // 小于2M的图片不进行压缩
      //     resolve(file)
      //   }
      //   // 文件压缩到指定的400kb
      //   imageConversion.compressAccurately(file, 400).then((res) => {
      //     console.log(res)
      //     resolve(res)
      //   })
      // })
      return this.$compress.compressImg(file)
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
